#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

typedef int ElemType;
typedef struct LNode{
    ElemType data;
    struct LNode *next;
}*LinkList, LNode;

bool initList(LinkList L);
int listLen(LinkList L);
bool listInsert(LinkList L, int index, ElemType elem);
bool listDelete(LinkList L, int index, ElemType *elem);
bool deleteNode(LNode *p);
bool insertNextNode(LNode *p, ElemType elem);
bool insertPriorNode(LNode *p, ElemType elem); 
LNode *locateElem(LinkList L, ElemType elem);
LNode *getElem(LinkList L, int index);

int main(){
    LinkList L;
    int temp = -1;
    initList(L);
    listInsert(L, 1, 100);
    listInsert(L, 2, 2000);
    listInsert(L, 3, 30000);
    printf("hand_node_data: %d\n", getElem(L, 0)->data);
    printf("first_node_data: %d\n", getElem(L, 1)->data);
    listDelete(L, 3, &temp);    //传入参数时，若参数是指针，则需要解指针后赋值。
    printf("%d\n", temp);
    int len = 0;
    len = listLen(L);
    printf("%d\n", len);
    return 0;
}

int listLen(LinkList L){
    int len = 1;
    LNode *p = L->next;
    while (p->next!=NULL){
        printf("%d\n", p->data);
        p = p->next;
        len++;
    }
    return len;
}

bool initList(LinkList L){
    L = (LNode *)malloc(sizeof(LNode));
    if(L==NULL) return false;
    L->next = NULL;
    return true;
}

bool listInsert(LinkList L, int index, ElemType elem){
    if(index<1) return false;
    // int id = 0;
    // LNode *p;
    // p = L;
    // while(p!=NULL&&id<index-1){
    //     p = p->next;
    //     id++;
    // }
    LNode *p = getElem(L, index-1);
    insertNextNode(p, elem);
}

bool insertNextNode(LNode *p, ElemType elem){
    if(p==NULL) return false;
    LNode *temp = (LNode *)malloc(sizeof(LNode));
    if(temp==NULL) return false;
    temp->data = elem;
    temp->next = p->next;
    p->next = temp;
    return true;
}

bool insertPriorNode(LNode *p, ElemType elem){
    if(p==NULL) return false;
    LNode *temp = (LNode *)malloc(sizeof(LNode));
    if(temp==NULL) return false;
    temp->data = p->data;
    temp->next = p->next;
    p->next = temp;
    p->data = elem;
    return true;
}

bool listDelete(LinkList L, int index, ElemType *elem){
    // if(index<1) return false;
    // int id = 0;
    // LNode *p;
    // p = L;
    // while(p!=NULL&&id<index-1){
    //     p = p->next;
    //     id++;
    // }
    LNode *p = getElem(L, index-1);
    if(p==NULL||p->next==NULL) return false;
    *elem = p->next->data;
    deleteNode(p);
}

bool deleteNode(LNode *p){
    if(p==NULL||p->next==NULL) return false;
    LNode *temp = p->next;
    p->next = temp->next;
    free(temp);
    return true;
}

LNode *locateElem(LinkList L, ElemType elem){
    LNode *p = L;
    while(L!=NULL&&L->data!=elem){
        p = p->next;
    }
    if(p==NULL||p->data!=elem) return NULL;
    return p;
}

LNode *getElem(LinkList L, int index){
    if(index<0) return NULL;
    LNode *p = L;
    int id = 0;
    while(p!=NULL && id<index){
        p = p->next;
        id++;
    }
    return p;
}